package net.sunbeta.test.control ;

import java.io.File ;
import java.util.Collection ;
import java.util.Enumeration ;
import java.util.Iterator ;

import net.sunbeta.test.util.ArrayToString ;

import org.apache.log4j.Logger ;
import org.apache.struts2.ServletActionContext ;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper ;

import com.opensymphony.xwork2.ActionSupport ;

public class FileUploadAction extends ActionSupport {

    private final Logger LOG = Logger.getLogger(FileUploadAction.class) ;

    public String execute() throws Exception {

        LOG.info("Starting upload file...") ;
        MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) ServletActionContext.getRequest() ;
        if (multiWrapper.hasErrors()) {
            Collection<String> errors = multiWrapper.getErrors() ;
            Iterator<String> i = errors.iterator() ;
            while (i.hasNext()) {
                addActionError((String) i.next()) ;
            }
            LOG.error("Uploading file failure!") ;
            return ERROR ;
        }

        Enumeration<String> e = multiWrapper.getFileParameterNames() ;
        while (e.hasMoreElements()) {
            // get the value of this input tag
            String inputValue = (String) e.nextElement() ;
            LOG.debug(String.format("The value of this input tag: %s", inputValue)) ;

            // get the content type
            String contentType = multiWrapper.getContentType() ;
            LOG.debug(String.format("The content type: %s", contentType)) ;

            // get the name of the file from the input tag
            String[] fileName = multiWrapper.getFileSystemNames(inputValue) ;
            LOG.debug(String.format("The names of the files from the input tag: %s", ArrayToString.get(fileName))) ;

            // Get a File object for the uploaded File
            File[] files = multiWrapper.getFiles(inputValue) ;

            // If it's null the upload failed
            if (files == null) {
                addActionError("Error uploading: " + multiWrapper.getFileSystemNames(inputValue)) ;
            }

            for (File file : files) {
                LOG.debug(String.format("The file name for the uploaded file: %s", file.getName())) ;
            }
        }

        return SUCCESS ;
    }

    private String message ;

    public void setMessage(String message) {
        this.message = message ;
    }

    public String getMessage() {
        return message ;
    }
}
